package com.hibernate.persistence.lifecycle;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class RefreshEntity {

	private static SessionFactory factory = new Configuration().configure().buildSessionFactory();
	private static Session session1;
	private static Session session2;

	public static void main(String[] args) {

		session1 = factory.openSession();
		session2 = factory.openSession();
		// session1, session2 isn't Same

		if (session1 == session2) System.out.println("session1 == session2");
		else System.out.println("session1 != session2");

		if (session1.equals(session2)) System.out.println("session1 equals session2");
		else System.out.println("session1 equals session2");

		System.out.println("session1 Before Get=" + session1.toString());
		System.out.println("session2 Before Get=" + session2.toString());

		Message msg1 = (Message) session1.get(Message.class, 3);
		Message msg2 = (Message) session2.get(Message.class, 4);

		msg1.setMessageText(msg1.getMessageText() + "changed");
		msg2.setMessageText(msg2.getMessageText() + "changed");

		System.out.println("session1 After Get=" + session1.toString());
		System.out.println("session2 After Get=" + session2.toString());

		session1.beginTransaction();
		session1.update(msg1);
		session1.getTransaction().commit();
		session1.close();
		
		msg1.setMessageText("");
		System.out.println("msg1=" + msg1);
		System.out.println("msg2=" + msg2);
		session2.refresh(msg1);
		System.out.println("msg1=" + msg1);
		System.out.println("msg2=" + msg2);
		
		System.out.println("session1 After Refresh=" + session1.toString());
		System.out.println("session2 After Refresh=" + session2.toString());
		
		session2.close();
	}
}
